#!/bin/bash
# Save user SSH public key if available.
# XXX: Obviously not suitable for downloadable images.

if [ ${DIB_DEBUG_TRACE:-0} -gt 0 ]; then
    set -x
fi
set -eu
set -o pipefail

if [ "$DIB_LOCAL_CONFIG_USERNAME" == "root" ]; then
    DIR_NAME=${DIB_LOCAL_CONFIG_USERNAME}
else
    DIR_NAME=home/${DIB_LOCAL_CONFIG_USERNAME}
fi

if [ -e "/tmp/in_target.d/ssh-authorized-keys" ]; then
    mkdir -p /${DIR_NAME}/.ssh
    cat /tmp/in_target.d/ssh-authorized-keys >> /${DIR_NAME}/.ssh/authorized_keys
    chmod 0700 /${DIR_NAME}/.ssh
    chmod 0600 /${DIR_NAME}/.ssh/authorized_keys
fi
